package com.xiake.zojcodesandbox;

import cn.hutool.core.date.StopWatch;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.model.*;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.ExecStartResultCallback;
import com.xiake.zojcodesandbox.enums.ExecuteStatusEnum;
import com.xiake.zojcodesandbox.model.ExecuteCodeRequest;
import com.xiake.zojcodesandbox.model.ExecuteCodeResponse;
import com.xiake.zojcodesandbox.model.ExecuteMessage;
import com.xiake.zojcodesandbox.model.JudgeInfo;
import com.xiake.zojcodesandbox.utils.ProcessUtils;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class JavaDockerCodeSandboxOld implements CodeSandbox {
    private static final String GLOBAL_CODE_DIR_NAME = "tmpCode";
    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";
    private static final long Max_Execute_Time = 5000;
    private static final long Max_Memory = 256;
    private static final String Max_Memory_Param = "-Xmx" + Max_Memory + "m";
    private static final Boolean FIRST_INIT = true;



    public static void main(String[] args) {
        JavaDockerCodeSandboxOld javaNativeCodeSandbox = new JavaDockerCodeSandboxOld();
        ExecuteCodeRequest executeCodeRequest = new ExecuteCodeRequest();
        executeCodeRequest.setInputList(Arrays.asList("1 2", "3 4"));
        String code = ResourceUtil.readStr("testCode/simpleComputeArgs/Main.java", StandardCharsets.UTF_8);
//        String code = ResourceUtil.readStr("testCode/unsafeCode/WriteFileError.java", StandardCharsets.UTF_8);
        executeCodeRequest.setCode(code);
        executeCodeRequest.setLanguage("java");

        ExecuteCodeResponse executeCodeResponse = javaNativeCodeSandbox.executeCode(executeCodeRequest);
        System.out.println(executeCodeResponse);
    }

    public  ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest){
        List<String> inputList = executeCodeRequest.getInputList();
        String code = executeCodeRequest.getCode();
        String language = executeCodeRequest.getLanguage();


        //1.把用户的代码保存为文件
        //"user.dir" 是Java系统属性中的一个键。这个属性表示Java应用程序的“用户工作目录”的路径。
        String userDir = System.getProperty("user.dir");  //获取当前工作目录
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;
        //判断文件夹是否存在
        if(!FileUtil.exist(globalCodePathName)){
            //不存在则创建
            FileUtil.mkdir(globalCodePathName);
        }
        //每次生成的目录都是不同的，用户代码隔离
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        //读取用户的代码内容写到指定的Main.java文件中
        File userCodeFile=FileUtil.writeString(code, userCodePath, "utf-8");


        //2.编译文件
        //编译命令：javac Main.java
        String compileCmd=String.format("javac -encoding utf-8 %s",userCodeFile.getAbsolutePath());
        try {
            Process compileProcess = Runtime.getRuntime().exec(compileCmd);
            ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(compileProcess, "编译");
            System.out.println(executeMessage);
        } catch (IOException e) {
            getErrorResponse(e);
        }

        //执行文件
        //1.拉取目标镜像
        DockerClient dockerClient = DockerClientBuilder.getInstance().build();
        String image="openjdk:8-alpine";
        if(FIRST_INIT){
            PullImageCmd pullImageCmd = dockerClient.pullImageCmd(image);
            PullImageResultCallback pullImageResultCallback = new PullImageResultCallback(){
                @Override
                public void onNext(PullResponseItem item) {
                    System.out.println("下载镜像状态:" + item.getStatus());
                    super.onNext(item);
                }
            };
            try {
                pullImageCmd
                        .exec(pullImageResultCallback)
                        .awaitCompletion(); // 等待下载完成，不然一直阻塞
            } catch (InterruptedException e) {
                System.out.println("拉取镜像异常！");
                throw new RuntimeException(e);
            }

            System.out.println("下载完成");
        }

        //2.创建一个可交互的容器,类比于容器池，一直有一个可运行的容器，而且有文件
        //在创建容器时，就将要编译的文件复制到文件
        CreateContainerCmd containerCmd = dockerClient.createContainerCmd(image);
        HostConfig hostConfig = new HostConfig();
        //将本地用户代码复制到容器内执行
        hostConfig.setBinds(new Bind(userCodeParentPath,new Volume("/app")));
        hostConfig.withMemory(100 * 1000 * 1000L);    //限制容器的内存大小
        hostConfig.withMemorySwap(0L);
        hostConfig.withCpuCount(1L);
        hostConfig.withMemorySwap(0L);
        hostConfig.withSecurityOpts(Arrays.asList("安全管理器的配置")); //限制用户的权限
        //seccomp的安全管理器的json
        CreateContainerResponse containerResponse = containerCmd
                .withHostConfig(hostConfig)
                .withNetworkDisabled(true)    //限制访问网络资源
                .withAttachStderr(true)   //获取本地的终端命令输入
                .withAttachStdin(true)
                .withAttachStdout(true)   //获取本地终端的输出
                .withTty(true)            //启用交互式容器
                .exec();
        String containerId = containerResponse.getId();


        //3.启动容器,把手动执行容器命令改为程序执行
        //docker start 6198822da9a0
        dockerClient.startContainerCmd(containerId).exec();

        //执行命令
        //docker exec 6198822da9a0 java -cp /app Main 1 2
        ExecCreateCmd execCreateCmd = dockerClient.execCreateCmd(containerId);
        ArrayList<ExecuteMessage>  executeMessageList= new ArrayList<>();
        for (String input : inputList) {
            StopWatch stopWatch = new StopWatch();
            //未输入参数的字符串
            String[] baseCmd=new String[]{"java","-cp","/app","Main"};
            //输入用例列表中的参数。如“1 2”,需要将数组中的每一个字符串进行拆分
            String[] param = input.split(" ");
            //最终组合成的命令
            String[] fullCmd = ArrayUtil.append(baseCmd, param);
            //创建要执行的命令
            ExecCreateCmdResponse execCreateCmdResponse = execCreateCmd
                    .withCmd(fullCmd)
                    .withAttachStderr(true)
                    .withAttachStdin(true)
                    .withAttachStdout(true)
                    .exec();
            System.out.println("创建执行命令"+execCreateCmdResponse);

            ExecuteMessage executeMessage = new ExecuteMessage();
            final String[] message = {null};
            final String[] errorMessage = {null};
            String execId = execCreateCmdResponse.getId();
            final boolean[] timeout={true};
            //执行刚才创建的命令
            ExecStartResultCallback execStartResultCallback = new ExecStartResultCallback(){
                @Override
                public void onComplete() { //在执行命令的回调函数去控制，即代码执行完判断是否超时
                    timeout[0]=false;
                    super.onComplete();
                }

                @Override
                public void onNext(Frame frame) {
                    StreamType streamType = frame.getStreamType();
                    if (StreamType.STDERR.equals(streamType)) {
                        errorMessage[0] = new String(frame.getPayload());
                        System.out.println("输出错误结果：" + errorMessage[0]);
                    } else {
                        message[0] = new String(frame.getPayload());
                        System.out.println("输出结果：" + message[0]);
                    }
                    super.onNext(frame);
                }
            };

            //监控内存占用状态
            //获得此段程序在docker容器中的执行状态
//            long maxMemory=0;
            final long[] maxMemory = {0L};
            StatsCmd statsCmd = dockerClient.statsCmd(containerId);
            statsCmd.exec(new ResultCallback<Statistics>() {
                @Override
                public void onStart(Closeable closeable) {

                }

                @Override
                public void onNext(Statistics statistics) {
                Long memoryUsage = statistics.getMemoryStats().getUsage();
                maxMemory[0]=Math.max(maxMemory[0],memoryUsage);
                 System.out.println(memoryUsage);


                }

                @Override
                public void onError(Throwable throwable) {

                }

                @Override
                public void onComplete() {

                }

                @Override
                public void close() throws IOException {

                }
            });

            try {
                stopWatch.start();
                dockerClient
                        .execStartCmd(execId)
                        .exec(execStartResultCallback)
                        .awaitCompletion(Max_Execute_Time, TimeUnit.MILLISECONDS); //超时就停止执行
                stopWatch.stop();
            } catch (InterruptedException e) {
                System.out.println("执行命令失败！");
                executeMessage.setExitValue(4);
                throw new RuntimeException(e);
            }


            //封装执行信息
            executeMessage.setErrorMessage(errorMessage[0]);
            executeMessage.setMessage(message[0]);
            executeMessage.setTime(stopWatch.getLastTaskTimeMillis());
            executeMessage.setMemory(maxMemory[0]);
            executeMessageList.add(executeMessage);
        }


        //4.整理输出结果
        long maxTime=0;
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        //将executeMessageList中的每一个ExecuteMessage对象转换为其getMessage方法的返回值，并将这些返回值收集到一个新的列表中。
        List<String> outPutMeassageList =new ArrayList<>();
        //对执行信息列表进行遍历，将每个执行信息对象中的message属性值取出来，并放入到新的列表中。
        for (ExecuteMessage executeMessage : executeMessageList) {
            String errorMessage = executeMessage.getErrorMessage();
            if(StrUtil.isNotBlank(executeMessage.getErrorMessage())){
                //如果执行信息对象中的errorMessage属性值不为空，则说明执行失败了
                //用户提交的代码错误
                executeCodeResponse.setMessage(ExecuteStatusEnum.USER_CODE_ERROR.getMessage());
                executeCodeResponse.setStatus(ExecuteStatusEnum.USER_CODE_ERROR.getStatus());
                break;
            }
            outPutMeassageList.add(executeMessage.getMessage());
            //找出最大执行时间
            Long time = executeMessage.getTime();
            if (time != null) {
                maxTime = Math.max(maxTime, time);
            }
        }
        executeCodeResponse.setOutputList(outPutMeassageList);
        if(executeMessageList.size()==outPutMeassageList.size()){
            //如果执行信息列表和输出结果列表的长度相同，说明每一条都执行成功，则设置状态为1
            executeCodeResponse.setStatus(ExecuteStatusEnum.SUCCESS.getStatus());
        }
        //设置JudgeInfo对象
        JudgeInfo judgeInfo = new JudgeInfo();
        // 取用时最大值，便于判断是否超时

        judgeInfo.setTime(maxTime);
//        judgeInfo.setMemory();

        executeCodeResponse.setJudgeInfo(judgeInfo);


        //5.删除用户代码目录
        if (userCodeFile.getParentFile() != null) {
            boolean del = FileUtil.del(userCodeParentPath);
            System.out.println("删除" + (del ? "成功" : "失败"));
        }

        return  executeCodeResponse;



//        //5，删除容器
//        dockerClient.removeContainerCmd(containerId).withForce(true).exec();


    }

    /**
     * 获取错误响应
     * @param e
     * @return
     */
    private ExecuteCodeResponse getErrorResponse(Throwable e) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        executeCodeResponse.setMessage(ExecuteStatusEnum.CODE_SANDBOX_ERROR.getMessage());
        // 表示代码沙箱错误
        executeCodeResponse.setStatus(ExecuteStatusEnum.CODE_SANDBOX_ERROR.getStatus());
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        return executeCodeResponse;
    }

}
